package com.iamteer.day22;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.SequenceInputStream;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Vector;

/**
主要回顾：SequenceStream
 */
public class SequenceStream {

	public static void main(String[] args) throws IOException {
//		merge1();
//		merge2();
//		merge3();
		merge4();
	}
	
	//逐个文件打开，读取，写入新文件
	public static void merge1() throws IOException {
		FileOutputStream out = new FileOutputStream("c.txt");
		FileInputStream in1 = new FileInputStream("a.txt");
		FileInputStream in2 = new FileInputStream("b.txt");
		
		byte[] buf = new byte[1024];
		int length = -1;
		
		while ((length = in1.read(buf)) != -1) {
			out.write(buf, 0, length);
		}
		in1.close();
		
		while ((length = in2.read(buf)) != -1) {
			out.write(buf, 0, length);
		}
		in2.close();
		out.close();
	}

	//使用 ArrayList 存放输入文件流，遍历 ArrayList 来打开读取，写入新文件
	public static void merge2() throws IOException {
		FileOutputStream out = new FileOutputStream("c.txt");
		FileInputStream in1 = new FileInputStream("a.txt");
		FileInputStream in2 = new FileInputStream("b.txt");
		
		ArrayList<FileInputStream> list = new ArrayList<FileInputStream>();
		list.add(in1);
		list.add(in2);
		
		byte[] b = new byte[1024];
		int len = -1;
		for (FileInputStream fileInputStream : list) {
			while ((len = fileInputStream.read(b)) != -1) {
				out.write(b, 0, len);
			}
			fileInputStream.close();
		}
		out.close();
	}

	//使用 SequenceInputStream(s1, s2)
	public static void merge3() throws IOException {
		FileOutputStream out = new FileOutputStream("c.txt");
		FileInputStream s1 = new FileInputStream("a.txt");
		FileInputStream s2 = new FileInputStream("b.txt");
		
		SequenceInputStream inputStream = new SequenceInputStream(s1, s2);
		byte[] b = new byte[1024];
		int len = -1;
		while ((len = inputStream.read(b)) != -1) {
			out.write(b, 0, len);
		}
		s2.close();
		s1.close();
		out.close();
	}
	
	//使用 SequenceInputStream(Enumeration<> e)
	public static void merge4() throws IOException {
		FileOutputStream out = new FileOutputStream("d.txt");
		FileInputStream s1 = new FileInputStream("a.txt");
		FileInputStream s2 = new FileInputStream("b.txt");
		FileInputStream s3 = new FileInputStream("c.txt");
		
		Vector<FileInputStream> vector = new Vector<FileInputStream>();
		vector.add(s1);
		vector.add(s2);
		vector.add(s3);
		
		Enumeration<FileInputStream> e = vector.elements();
		
		SequenceInputStream inputStream = new SequenceInputStream(e);
		byte[] b = new byte[1024];
		int len = -1;
		while ((len = inputStream.read(b)) != -1) {
			out.write(b, 0, len);
		}
		inputStream.close();
		out.close();
	}
	
	
}
